//
// Created by kuang on 2024/11/25.
//

#ifndef PCAP_UTILS_H
#define PCAP_UTILS_H

#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <arpa/inet.h>
#include <stdlib.h>

// PCAP全局头结构
struct pcap_global_header {
    uint32_t magic_number;
    uint16_t version_major;
    uint16_t version_minor;
    int32_t thiszone;
    uint32_t sigfigs;
    uint32_t snaplen;
    uint32_t network;
};

// PCAP数据包头结构
struct pcap_packet_header {
    uint32_t ts_sec;
    uint32_t ts_usec;
    uint32_t incl_len;
    uint32_t orig_len;
};

// 以太网头部结构
struct ethernet_header {
    uint8_t dst_mac[6];
    uint8_t src_mac[6];
    uint16_t ethertype;
};

// IP头部结构
struct ip_header {
    uint8_t version_ihl;
    uint8_t tos;
    uint16_t total_length;
    uint16_t identification;
    uint16_t flags_fragment_offset;
    uint8_t ttl;
    uint8_t protocol;
    uint16_t header_checksum;
    uint32_t src_ip;
    uint32_t dst_ip;
};

// UDP头部结构
struct udp_header {
    uint16_t src_port;
    uint16_t dst_port;
    uint16_t length;
    uint16_t checksum;
};

// 函数声明
// 内存操作函数
uint32_t write_pcap_global_header_to_buffer(uint8_t *buffer);
uint32_t write_udp_packet_to_buffer(uint8_t *buffer,
                                    const uint8_t *src_mac, const uint8_t *dst_mac,
                                    uint32_t src_ip, uint32_t dst_ip,
                                    uint16_t src_port, uint16_t dst_port,
                                    const uint8_t *payload, uint16_t payload_length);

// 文件操作函数
void write_pcap_global_header_to_file(FILE *fp);
void write_udp_packet_to_file(FILE *fp,
                              const uint8_t *src_mac, const uint8_t *dst_mac,
                              uint32_t src_ip, uint32_t dst_ip,
                              uint16_t src_port, uint16_t dst_port,
                              const uint8_t *payload, uint16_t payload_length);

// 解析函数
void parse_pcap_buffer(const uint8_t *buffer, uint32_t buffer_length);

// 辅助函数
uint16_t calculate_checksum(uint16_t *addr, int len);
void print_hex_dump(const uint8_t *data, int len);
char* mac_addr_to_str(const uint8_t *mac_addr, char *str, size_t size);
char* ip_addr_to_str(uint32_t ip_addr, char *str, size_t size);

#endif // PCAP_UTILS_H
